import subprocess
import rrd_base
import re
import time

import color

try:
    import boto
    from pyrrd.rrd import DataSource, RRA, RRD
    from pyrrd.graph import DEF, CDEF, VDEF
    from pyrrd.graph import LINE, AREA, GPRINT
    from pyrrd.graph import ColorAttributes, Graph
except:
    print "Couldn't load required modules. You probably need to install it with:"
    sys.exit('sudo apt-get install python-pyrrd python-pysnmp4 python-boto')

class RrdS3Du(rrd_base.RrdBase):
    def __init__(self, domain, name):
        super(RrdS3Du,self).__init__(domain=domain, group="filesystem", instance=name)

    def data_step(self):
        return 60*60

    def create_file(self):
        dataSources = []
        dataSources.append(DataSource( dsName='usage', dsType='GAUGE', heartbeat=self.heartbeat()))

        roundRobinArchives = []
        for func in ['AVERAGE', 'MAX', 'MIN']:
            for step,row in self.rra_pattern():
                roundRobinArchives.append(RRA(cf=func, xff=0.5, steps=step, rows=row))

        self.myRRD = RRD(self.filename, ds=dataSources, rra=roundRobinArchives, step=self.data_step())
        self.myRRD.create()

    def update(self):
        buckets_size = 0
        s3 = boto.connect_s3()
        for bucket in s3.get_all_buckets():
            for k in bucket.list():
                buckets_size += k.size

        self.myRRD.bufferValue(int(round(time.time())), buckets_size)
        self.myRRD.update()

    def graph(self):
        d_avg  =  DEF(rrdfile=self.myRRD.filename, vname='a', cdef="AVERAGE", dsName='usage')
        d_max  =  DEF(rrdfile=self.myRRD.filename, vname='b', cdef="MAX", dsName='usage')
        d_min  =  DEF(rrdfile=self.myRRD.filename, vname='c', cdef="MIN", dsName='usage')
        v_peak = VDEF(vname="v0",      rpn="{0},MAXIMUM".format(d_max.vname))
        line_0 = LINE(1,defObj=d_max,  color=color.RGBA['red'],   legend="Max")
        line_1 = LINE(1,defObj=d_min,  color=color.RGBA['blue'],  legend="Min")
        line_2 = LINE(2,defObj=v_peak, color=color.RGBA['black'], legend="Peak")
        area_0 = AREA(defObj=d_avg,    color=color.RGBA['green'], legend="Usage")

        for tf in self.graph_time_frames().keys():
            g = Graph(self.image_name(tf),
                      start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                      lower_limit=1,
                      title='"S3 Usage - Updated {0}"'.format(time.strftime("%Y%m%d at %H:%M")),
                      vertical_label='Bytes',
                      height=self.graph_height, width=self.graph_width,
                      x_grid=self.grid[tf],
                      step=self.graph_step_times[tf])
            g.data.extend([d_avg, area_0, d_max, v_peak, line_2])
            if self.graph_time_frames()[tf] > self.graph_time_frames()["1day"]:
                g.data.extend([d_min, line_0, line_1])
            g.write()

            if False:
                g = Graph(self.icon_name(tf),
                          start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                          lower_limit=1,
                          no_legend=True,
                          height=self.icon_height, width=self.icon_width,
                          step=self.graph_step_times[tf])
                g.data.extend([d_avg, area_0])
                g.write()
